package com.jinzhi.sys.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.msg.PackTemplateMap;
import com.jinzhi.jzapi.msg.WxPushServiceQcl;
import com.jinzhi.jzapi.msg.domain.TemplateData;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ChapterItemBankVo;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.service.ExpertsService;
import com.jinzhi.jzweb.service.MsgService;
import com.jinzhi.jzweb.service.MsgTemplateService;
import com.jinzhi.jzweb.service.OrganizationNewsService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.RoleDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.domain.vo.UserVo;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.sys.vo.UserVO;
import com.jinzhi.wxmp.domain.MpConfigDO;
import com.jinzhi.wxmp.service.MpConfigService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <pre>
 * </pre>
 * <p>
 * <small> 2018年3月23日 | Aron</small>
 */
@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {
    private String prefix = "sys/user";
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    DictService dictService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private MsgTemplateService msgTemplateService;
    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;
    @Autowired
    private MpConfigService mpConfigService;
    @Autowired
    private UserRoleService userRoleService;

    @Log("进入系统用户列表页面")
    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        return prefix + "/user";
    }

    @Scheduled(cron = "0 0 23 * * ?")


    @Log("查询系统用户列表")
    @GetMapping("/list")
    @ResponseBody
    public Result<Page<UserDO>> list(UserDO userDTO) {
        Wrapper<UserDO> wrapper = new EntityWrapper<UserDO>().orderBy("id", false);
        if (userDTO.getSex() != null) {
            wrapper.eq("sex", userDTO.getSex());
        }
        if (userDTO.getStatus() != null) {
            wrapper.eq("status", userDTO.getStatus());
        }
        if (userDTO.getType() != null) {
            wrapper.eq("type", userDTO.getType());
        }
        if (userDTO.getName() != null) {
            wrapper.like("name", userDTO.getName());
        }
        if (userDTO.getUsername() != null) {
            wrapper.like("username", userDTO.getUsername());
        }
        if (userDTO.getMobile() != null) {
            wrapper.like("mobile", userDTO.getMobile());
        }
        if (userDTO.getState() != null) {
            wrapper.eq("state", userDTO.getState());
        }
        if (StringUtils.isNotBlank(userDTO.getOrgName())) {
            Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().like("name", userDTO.getOrgName());
            List<OrganizationNewsDO> organizationNewsDOS = organizationNewsService.selectList(orWrapper);
            String str = "";
            for (OrganizationNewsDO organizationNewsDO : organizationNewsDOS) {
                str = str + organizationNewsDO.getId() + ",";
            }
            wrapper.and();
            if (StringUtils.isNotBlank(str)) {
                wrapper.in("orgId", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("orgId", null);
            }
        }

        Page<UserDO> page = userService.selectPage(getPage(UserDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            UserDO obj = (UserDO) page.getRecords().get(i);
            if (obj.getOrgId() != null) {
                OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
                if (organizationNewsDO != null) {
                    obj.setOrgName(organizationNewsDO.getName());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }


    @RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @GetMapping("/add")
    String add(Model model) {
        List<RoleDO> roles = roleService.selectList(null);
        model.addAttribute("roles", roles);
        model.addAttribute("organizationNews", organizationNewsService.selByOrgId());
        return prefix + "/add";
    }

    @RequiresPermissions("sys:user:edit")
    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Long id) {
        UserDO userDO = userService.selectById(id);
        model.addAttribute("user", userDO);
        List<RoleDO> roles = roleService.findListStatusByUserId(id);
        model.addAttribute("roles", roles);
        Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().orderBy("name");
        model.addAttribute("organizationNews", organizationNewsService.selectList(orWrapper));
        return prefix + "/edit";
    }

    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:user:user")
    String info(@PathVariable("id") Long id, Model model) {
        UserDO userDO = userService.selectById(id);
        model.addAttribute("user", userDO);
        return prefix + "/info";
    }

    @GetMapping("/importUser")
//    @RequiresPermissions("sys:user:importUser")
    String importUser( Model model) {

        return prefix + "/importUser";
    }

    @RequiresPermissions("sys:user:add")
    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    Result<String> save(UserDO user) {
        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(user.getOrgId());
        if (organizationNewsDO != null) {
            user.setOrgName(organizationNewsDO.getName());
        }
        user.setState(3);
        userService.insert(user);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/update")
    @ResponseBody
    Result<String> update(UserDO user) {
        //同时更新专家表的所属机构id
        List<ExpertsDO> expertsDOS = expertsService.findByKv("user_id", user.getId());
        if (expertsDOS != null && expertsDOS.size() > 0) {
            List<ExpertsDO> expertsDOS1 = new ArrayList<>();
            for (ExpertsDO expertsDO : expertsDOS) {
                //if(user.getOrgId() != null){
                //  if(expertsDO.getOrgId() != null){
                if (!expertsDO.getOrgId().equals(user.getOrgId())) {
                    expertsDO.setOrgId(user.getOrgId());
                    expertsDOS1.add(expertsDO);

                } else {
                    expertsDO.setOrgId(user.getOrgId());
                    expertsDOS1.add(expertsDO);
                }
                //  }
            }

            if (expertsDOS1.size() > 0) {
                expertsService.updateBatchById(expertsDOS1, expertsDOS1.size());
            }
        }
        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(user.getOrgId());
        if (organizationNewsDO != null) {
            user.setOrgName(organizationNewsDO.getName());
        } else {
            user.setOrgName(null);
            user.setOrgId(null);
            userService.updayeOrg(user);
        }

        userService.updateById(user);

        return Result.ok();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/updatePeronal")
    @ResponseBody
    Result<String> updatePeronal(UserDO user) {
        userService.updatePersonal(user);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:remove")
    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    @Transactional
    Result<String> remove(Long id) {
        boolean b = userService.deleteById(id);
        if (b) {
            List<ExpertsDO> expertsDOS = expertsService.findByKv("user_id", id);
            if (expertsDOS != null && expertsDOS.size() > 0) {
                List<Long> ids = new ArrayList<>();
                for (ExpertsDO expertsDO : expertsDOS) {
                    ids.add(expertsDO.getId());
                }
                boolean cc = expertsService.deleteBatchIds(ids);
                if (cc) {
                    return Result.ok();
                } else {
                    return Result.fail();
                }
            }
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    @RequiresPermissions("sys:user:batchRemove")
    @Log("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    @Transactional
    Result<String> batchRemove(@RequestParam("ids[]") Long[] userIds) {
        boolean b = userService.deleteBatchIds(Arrays.asList(userIds));
        if (b) {
            boolean ccd = true;
            for (Long id : userIds) {
                List<ExpertsDO> expertsDOS = expertsService.findByKv("user_id", id);
                if (expertsDOS != null && expertsDOS.size() > 0) {
                    List<Long> ids = new ArrayList<>();
                    for (ExpertsDO expertsDO : expertsDOS) {
                        ids.add(expertsDO.getId());
                    }
                    ccd = expertsService.deleteBatchIds(ids);
                }
            }
            if (ccd) {
                return Result.ok();
            } else {
                return Result.fail();
            }
        } else {
            return Result.fail();
        }
    }

    @PostMapping("/exist")
    @ResponseBody
    boolean exist(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exist(params);
    }

    @RequiresPermissions("sys:user:resetPwd")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {
        UserDO userDO = new UserDO();
        userDO.setId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    Result<String> resetPwd(UserVO userVO) {
        userService.resetPwd(userVO, getUser());
        return Result.ok();
    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    Result<String> adminResetPwd(UserVO userVO) {
        userService.adminResetPwd(userVO);
        return Result.ok();

    }

    @RequiresPermissions("sys:user:add")
    @Log("审核")
    @PostMapping("/review")
    @ResponseBody
    Result<String> check(@RequestParam("ids[]") Long[] ids, Integer state, String remark) {

        //查询字典:消息模板
        DictDO dic = null;
        String valStr = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (state == 2) {
            dic = dictService.findOneByKv("type", "check_no_pass");
            valStr = dic.getValue().replace("{value4}", remark);
        } else {
            dic = dictService.findOneByKv("type", "check_pass");
            valStr = dic.getValue();
        }
        valStr = valStr.replace("{value1}", "个人信息");
        valStr = valStr.replace("{value2}", this.getUser().getUsername());
        valStr = valStr.replace("{value3}", formatter.format(new Date()));

        for (Long id : ids) {
            UserDO user = userService.selectById(id);
            user.setState(state);

            MsgDO msg = new MsgDO();
            if (state == 1) {
                msg.setTitle("您的个人信息审核通过！");
                user.setRemark("");
            } else {
                msg.setTitle("您的个人信息审核未通过！");
                user.setRemark(remark);
            }
            msg.setContent(valStr);
            msg.setCreaterId(this.getUserId());
            msg.setCreaterDate(new Date());
            msg.setType(1);
            msg.setMsgType(0);
            msg.setUserId(id);
            msg.setState(0);
            if (userService.updateById(user)) {
                msgService.insert(msg);

                //------------------------订阅消息模块-----------------------------\
                MsgTemplateDO msgTemplate = msgTemplateService.findOneByKv("type", 0, "temp_ip", user.getLastEdit());
//                UserDO user = userService.selectById(expertsDO.getUserId());
                if (user.getCerOpenId() != null || user.getTraOpenId() != null) {
                    if (msgTemplate != null) {
                        String[] value = null;
                        if (state == 1) {//通过
                            MsgTemplateDO templateDO = msgTemplateService.findOneByKv("pid", msgTemplate.getId(), "type", 2, "temp_ip", user.getLastEdit());
                            value = templateDO.getContent().split("/n");
                            for (int a = 0; a < value.length; a++) {
                                value[a] = value[a].replace("{value1}", "个人信息");
                                value[a] = value[a].replace("{value2}", "个人信息");
                                value[a] = value[a].replace("{date}", formatter.format(new Date()));
                            }
                        } else if (state == 2) {//未通过
                            MsgTemplateDO templateDO = msgTemplateService.findOneByKv("pid", msgTemplate.getId(), "type", 3, "temp_ip", user.getLastEdit());
                            value = templateDO.getContent().split("/n");
                            for (int a = 0; a < value.length; a++) {
                                value[a] = value[a].replace("{value1}", "个人信息");
                                value[a] = value[a].replace("{value2}", "个人信息");
                                value[a] = value[a].replace("{remark}", remark);
                                value[a] = value[a].replace("{date}", formatter.format(new Date()));
                            }
                        }
                        String[] parm = msgTemplate.getContent().split(",");
                        Map<String, TemplateData> map = PackTemplateMap.get1(value, parm);

                        MpConfigDO mc = mpConfigService.selectById(user.getLastEdit());
                        if (user.getLastEdit() == 101) {
                            wxPushServiceQcl.sendMsgToUser(mc.getId().intValue(), user.getCerOpenId(), msgTemplate.getCode(), map, "pages/userInfo/userInfo");
                        } else {
                            wxPushServiceQcl.sendMsgToUser(mc.getId().intValue(), user.getTraOpenId(), msgTemplate.getCode(), map, "pages/userInfo/userInfo");
                        }


                    }
                }
                //------------------------订阅消息模块结束-----------------------------\

            }

        }
        return Result.ok();
    }


    @GetMapping("/treeView")
    String treeView() {
        return prefix + "/userTree";
    }

    @GetMapping("/personal")
    String personal(Model model) {
        UserDO userDO = userService.selectById(getUserId());
        model.addAttribute("user", userDO);
        List<DictDO> hobbyList = dictService.getHobbyList(userDO);
        model.addAttribute("hobbyList", hobbyList);
        List<DictDO> sexList = dictService.getSexList();
        model.addAttribute("sexList", sexList);
        return prefix + "/personal";
    }

    @GetMapping("/adminMessage")
    String adminMessage(Model model, String state) {
        model.addAttribute("state", state);
        return prefix + "/adminMessage";
    }

    @Log("上传头像")
    @ResponseBody
    @PostMapping("/uploadImg")
    Result<?> uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request)
            throws Exception {
        Map<String, Object> result = new HashMap<>();
        result = userService.updatePersonalImg(file, avatar_data, getUserId());
        return Result.ok(result);
    }


    @Log("消息中心列表")
    @GetMapping("/msgList")
    @ResponseBody
    Result<?> msgList(int current, int number, String state, String type) {
        UserDO user = this.getUser();
        Map map = new HashMap();
        map.put("userId", user.getId());
        map.put("state", state);
        map.put("type", type);
        Page<MsgDO> page = msgService.selMsgPage(current, number, map);
        List<MsgDO> list = page.getRecords();
        for (MsgDO msg : list) {
            msg.setUserName(user.getUsername());
            UserDO user1 = userService.selectById(msg.getCreaterId());
            msg.setCreaterName(user1.getUsername());
        }
        page.setRecords(list);
        return Result.ok(page);
    }


    @Log("消息中心更改状态")
    @GetMapping("/updateState")
    @ResponseBody
    Result<?> updateState(Long id) {
        MsgDO msg = msgService.selectById(id);
        msg.setState(2);
        msgService.updateById(msg);
        return Result.ok();
    }


    @Log("未读消息条数")
    @GetMapping("/unreadNum")
    @ResponseBody
    Result<?> unreadNum(String type) {
        if (getUser() != null) {
            List<MsgDO> msg = msgService.findByKv("state", 0, "userId", this.getUserId(), "type", type);
            return Result.ok(msg.size());
        } else {
            return Result.ok(0);
        }

    }

    /**
     * 下载导入模板
     *
     * @param response
     */
    @RequestMapping("/downloadImportTemplate")
    @RequiresPermissions("sys:user:downloadImportTemplate")
    @ResponseBody
    public void downloadImportTemplate(HttpServletResponse response) {
        List<UserVo> list = new LinkedList<>();
        //导出操作
        EasyPoiUtil.exportExcel(list, "用户信息导入模板", "用户信息导入模板", UserVo.class, "用户信息导入模板", response);
    }

    @PostMapping("/import")
    @ResponseBody
    @Transactional
    public Result<?> importExcel(@RequestParam("file") MultipartFile file, Integer userSource) {
        //---------------------------------检测导入信息及条件-----------------------------------------
        // 第一步--判断文件格式
        if (!"application/vnd.ms-excel".equals(file.getContentType())) {
            return Result.fail("文件格式错误，请选择.xls文件");
        }

        // 第二步--解析文件获得数据
        List<UserVo> list = EasyPoiUtil.importExcel(file, 1, 1, UserVo.class);
        if (list.size() == 0) {
            return Result.fail("Excel数据为空，请完善");
        }

        //---------------------------------验证数据并导入-----------------------------------------
        int startRow = 3; // 数据开始的行号（Excel 第三行）
        int cout = 1; // 错误信息计数
        List<UserDO> userDOS = new ArrayList<>(); // 用于批量插入用户数据
        List<UserRoleDO> userRoleDOS = new ArrayList<>(); // 用于批量插入用户-角色关联数据
        List<ErrorCodeVo> list1 = new ArrayList<>(); // 用于存储错误信息
        for (int i = 0; i < list.size(); i++) {
            StringBuilder sb = new StringBuilder();
            UserDO userDO = userService.selectOne(new EntityWrapper<UserDO>().eq("mobile",list.get(i).getMobile()).ne("user_source",1));
            UserDO userDO1 = userService.selectOne(new EntityWrapper<UserDO>().eq("username",list.get(i).getUsername()).ne("user_source",1));
            // 验证是否存在空值
            if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getName())) {
                sb.append("第" + (i + startRow) + "行姓名未填写，请完善！" + ";");
            } else if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getUsername())) {
                sb.append("第" + (i + startRow) + "行用户名未填写，请完善！" + ";");
            } else if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getMobile())) {
                sb.append("第" + (i + startRow) + "行手机号未填写，请完善！" + ";");
            } else if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getRoleNameList())) {
                sb.append("第" + (i + startRow) + "行角色未填写，请完善！" + ";");
            } else if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getType())) {
                sb.append("第" + (i + startRow) + "行会员类型未填写，请完善！" + ";");
            }else if (userDO!=null){
                sb.append("第" + (i + startRow) + "行手机号已存在！" + ";");
            }
            else if (userDO1!=null){
                sb.append("第" + (i + startRow) + "行用户名已存在！" + ";");
            }

            if (sb.length() > 0) {
                ErrorCodeVo errorCodeVo = new ErrorCodeVo();
                errorCodeVo.setSeq(cout);
                cout += 1;
                errorCodeVo.setErrorCode(sb.toString());
                list1.add(errorCodeVo);
            } else {
                //来源为小程序的可以删除，然后新增
                userDO = userService.selectOne(new EntityWrapper<UserDO>().eq("mobile",list.get(i).getMobile()).eq("user_source",1));
                if (userDO!=null){
                    userService.deleteById(userDO.getId());
                }
                userDO=new UserDO();
                userDO.setMobile(list.get(i).getMobile());
                userDO.setUserSource(userSource);
                userDO.setUsername(list.get(i).getUsername());
                userDO.setName(list.get(i).getName());
                userDO.setType(Integer.valueOf(list.get(i).getType()));
                userDO.setStatus(1);
                userDO.setGmtCreate(new Date());
                userDOS.add(userDO);

                // 处理角色名称
                String roleNameList = list.get(i).getRoleNameList();
                if (roleNameList != null) {
                    if (roleNameList.contains("普通用户")) {
                        UserRoleDO userRoleDO = new UserRoleDO();
                        userRoleDO.setRoleId(56L);
                        userRoleDOS.add(userRoleDO);
                    }
                    if (roleNameList.contains("开通练习权限")) {
                        UserRoleDO userRoleDO = new UserRoleDO();
                        userRoleDO.setRoleId(1821091094336851970L);
                        userRoleDOS.add(userRoleDO);
                    }
                }
            }
        }

        if (list1.size() == 0) {
            // 先批量插入用户信息
            boolean userInsertResult = userService.insertBatch(userDOS, userDOS.size());

            if (userInsertResult) {
                // 获取刚插入的用户的 ID
                List<UserDO> insertedUsers = userService.getUsersByMobileList(
                        userDOS.stream().map(UserDO::getMobile).collect(Collectors.toList())
                );

                // 创建用户ID与角色ID的映射
                Map<Long, List<Long>> userRolesMap = new HashMap<>();
                for (UserDO user : insertedUsers) {
                    List<Long> roles = new ArrayList<>();
                    if (userRoleDOS.stream().anyMatch(role -> role.getRoleId() == 56L)) {
                        roles.add(56L);
                    }
                    if (userRoleDOS.stream().anyMatch(role -> role.getRoleId() == 1821091094336851970L)) {
                        roles.add(1821091094336851970L);
                    }
                    userRolesMap.put(user.getId(), roles);
                }

                // 生成 UserRoleDO 对象并批量插入
                List<UserRoleDO> userRoleInsertList = new ArrayList<>();
                for (Map.Entry<Long, List<Long>> entry : userRolesMap.entrySet()) {
                    Long userId = entry.getKey();
                    List<Long> roleIds = entry.getValue();
                    for (Long roleId : roleIds) {
                        UserRoleDO userRoleDO = new UserRoleDO();
                        userRoleDO.setUserId(userId);
                        userRoleDO.setRoleId(roleId);
                        userRoleInsertList.add(userRoleDO);
                    }
                }

                boolean roleInsertResult = userRoleService.insertBatch(userRoleInsertList, userRoleInsertList.size());
                if (roleInsertResult) {
                    return Result.ok("成功导入" + list.size() + "条数据");
                } else {
                    return Result.fail("用户角色关联信息导入错误，请稍后重试或联系管理员");
                }
            } else {
                return Result.fail("用户信息导入错误，请稍后重试或联系管理员");
            }
        } else {
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
            // 将 list1 存到缓存中
            EhCacheUtil.put("userDo" + this.getUserId(), jsonArray);
            return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
        }
    }

    /**
     * 导出错误信息
     *
     * @param request
     * @param response
     * @throws Exception
     * @author kl
     */
    @Log("导出错误信息")
    @GetMapping("/importError")
    @ResponseBody
    @Transactional
//    @RequiresPermissions("jzweb:chapterItemBank:import")
    public void download(javax.servlet.http.HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户导入错误信息", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        String jsonArray = EhCacheUtil.get("userDo" + this.getUserId()).toString();
        JSONArray arrayList = JSONArray.parseArray(jsonArray);
        //转换为目标对象list
        List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
        workbook.write(response.getOutputStream());
    }
}